<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" >
         <el-form-item label="考题题目" prop="quesTitle">
            <el-input
               v-model="queryParams.quesTitle"
               placeholder="请输入考题题目"
               clearable
               style="width: 200px"
              
            />
         </el-form-item>
            <el-form-item label="考题类型:" prop="quesType">
              <el-select v-model="queryParams.quesType" clearable placeholder="请选择考题类型">
                <el-option
                  v-for="dict in quesTypeList"
                  :key="dict.dictCode"
                  :label="dict.dictLabel"
                  :value="dict.dictCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上传时间" >
            <el-date-picker
                     v-model="dateRange"
                     value-format="YYYY-MM-DD HH:mm"
                     type="daterange"
                     range-separator="-"
                     start-placeholder="开始日期"
                     end-placeholder="结束日期"
                     :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                  ></el-date-picker>
          </el-form-item>
         <el-form-item>
            <el-button color="#265DA4" :dark="isDark" icon="Search" @click="handleQuery" v-hasPermi="['manager:stashQuestion:query']" >搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button
               color="#265DA4"
               plain
               icon="Plus"
               @click="handleAdd"
               v-hasPermi="['manager:stashQuestion:add']"
            >新增</el-button>
         </el-col>
         <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermi="['manager:stashQuestion:import']"
          >导入</el-button
        >
      </el-col>
      </el-row>

      <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
         <el-table-column label="序号" align="left" type="index" width="100" />
         <el-table-column label="考题题目" align="left" prop="quesTitle"  />
         <el-table-column label="考题类型" align="left" prop="quesTypeName" width="150"  />
         <el-table-column label="考题分值" align="left" prop="quesScore" width="100" />
         <el-table-column label="上传时间" align="left" prop="createTime" width="180" />
         <el-table-column label="操作" align="left" width="300" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button link style="color:#265DA4;" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manager:stashQuestion:edit']">修改</el-button>
               <el-button link style="color:#265DA4;" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manager:stashQuestion:remove']" >删除</el-button>
            </template>
         </el-table-column>
      </el-table>

      <pagination
         v-show="total > 0"
         :total="total"
         v-model:page="queryParams.pageNum"
         v-model:limit="queryParams.pageSize"
         @pagination="getList"
      />

      <!-- 添加或修改对话框 -->
      <el-dialog :title="title" v-model="open" width="780px" append-to-body
      class="dialogClass" 
    >
      <template #title>
         
        <span>{{title}}</span>
      </template>
        <el-radio-group v-model="questionType" style="margin-bottom: 30px" size="large">
          <el-radio-button  
                v-for="dict in questypeList1"
                :key="dict.dictCode"
                :label="dict.dictLabel"
                :name="dict.dictLabel"
                >
              </el-radio-button>
        </el-radio-group>

         <el-form ref="noticeRef" :model="form" :rules="rules" label-width="100px"> 
            <el-row>
               <el-col :span="24">
                <el-form-item label="考题分值:" prop="quesScore">
                    <el-input 
                      v-model="form.quesScore"
                      placeholder="请输入考题分值"
                      clearable
                      type="number"
                      class="inputDeep"
                    />
                </el-form-item>
                <el-form-item label="考&nbsp;&nbsp;&nbsp;点ID:" prop="siteId">
                    <el-select v-model="form.siteId" placeholder="请选择考题类型"> 
                      <el-option
                        v-for="dict in siteIdList"
                        :key="dict.dictCode"
                        :label="dict.dictLabel"
                        :value="dict.dictCode"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="考题类型:" prop="quesType">
                    <el-select v-model="form.quesType" placeholder="请选择考题类型"> 
                      <el-option
                        v-for="dict in quesTypeList"
                        :key="dict.dictCode"
                        :label="dict.dictLabel"
                        :value="dict.dictCode"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="难&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;度:" prop="quesLevel">
                    <el-radio-group v-model="form.quesLevel">
                     <el-radio
                           v-for="dict in quesLevelList"
                           :key="dict.dictCode"
                           :label="dict.dictCode"
                        >{{ dict.dictLabel }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="考试题目:" prop="quesTitle">
                    <editor v-model="form.quesTitle" :min-height="120"/>
                  </el-form-item>
                  <el-form-item label="选&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;项:"  v-if="questionType != '判断题'">
                    <el-table border :data="answList">
                      <el-table-column label="选项文字" align="left" prop="answContent" >
                        <template #default="scope">
                          <el-input v-model="scope.row.answContent"></el-input>    
                        </template>
                      </el-table-column>
                      <el-table-column label="" align="left" >
                          <template #default="scope">
                            <el-icon @click="handleAddItem(scope.$index)" class="editIcon"><CirclePlusFilled /></el-icon>
                            <el-icon @click="handleMunisItem(scope.$index)" class="editIcon"><RemoveFilled /></el-icon>
                          </template>
                      </el-table-column>
                      <el-table-column label="正确答案" align="left" prop="answFlag" >
                        <template #default="scope">
                          <!-- <el-radio v-if="questionType == 0" v-model="scope.row.answFlag" ></el-radio> -->
                          <el-checkbox v-model="scope.row.answFlag"  size="large" />
                        </template>
                      </el-table-column>
                      
                      <el-table-column label="上移下移" align="left" >
                          <template #default="scope">
                            <el-icon @click="handleUpItem(scope.$index)" class="editIcon"><Top /></el-icon>
                            <el-icon @click="handleDownItem(scope.$index)" class="editIcon"><Bottom /></el-icon>
                          </template>
                      </el-table-column>
                    </el-table>
                  </el-form-item>
                  <el-form-item label="答&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;案:" prop="quesAnswer" v-if="questionType == '判断题'">
                      <el-radio-group v-model="form.quesAnswer">
                        <el-radio label="true">正确</el-radio>
                        <el-radio label="false">错误</el-radio>
                      </el-radio-group>
                    </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button color="#265DA4" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
      <!-- 文件导入弹框 -->
    <el-dialog
      v-model="upload.open"
      width="400px"
      append-to-body
      class="dialogClass" 
    >
      <template #title>
         
        <span>{{upload.title}}</span>
      </template>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              color="#265DA4"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button color="#265DA4" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false" color="#265DA4" plain>取 消</el-button>
        </div>
      </template>
    </el-dialog>
   </div>
</template>

<script setup name="Notice">
import { stashQuestionList, stashQuestionAdd, stashQuestionEdit, stashQuestionRomove } from "@/api/question/question";
import { questionTypeList } from "@/api/question/classification";
import { pointTypeList} from "@/api/question/examPlace";
import { listData } from "@/api/system/dict/data";
import { getListItemNumber } from '@/utils/common';
import {getToken} from "@/utils/auth";
const { proxy } = getCurrentInstance();

const siteIdList = ref([])
const quesLevelList = ref([])
const questypeList1 = ref([])
const quesTypeList = ref([]);
const questionList = ref([]);
const dateRange = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const questionType = ref("单选题");
const answList = ref([
  {
    answContent: '',
    answFlag: false, 
  },
  
]);
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "导入",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/manager/stashQuestion/import",
});
const data = reactive({
  form: { 
    quesType:'', 
    quesLevel:0,
    questionType:'',
    quesTitle:'',
    quesScore:'',
    answList:[],
    quesAnswer:''
  },
  queryParams: {
    pageSize: 10,
    pageNum:1,
    quesType: '',
    quesTitle:'',
  },
  rules: {
    quesScore: [{ required: true, message: "考题分值不能为空", trigger: "blur" }], 
    quesType: [{ required: true, message: "考题类型不能为空", trigger: "blur" }], 
    siteId: [{ required: true, message: "考题ID不能为空", trigger: "blur" }],
    quesType: [{ required: true, message: "考题类型不能为空", trigger: "blur" }],
    quesLevel: [{ required: true, message: "请选择考题难度", trigger: "blur" }],
    quesTitle: [{ required: true, message: "考题内容不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};
/** 下载模板操作 */
function importTemplate() {
  // let url = 'http://192.168.10.235:9000/document/2023/09/22/948d2ab3102a4ddfaa57639364ace28e.xls'
  // const link = document.createElement("a");
  // link.href = url;
  // link.setAttribute("download", '模板');
  // link.click();

  proxy.download(
    "manager/stashQuestion/importTemplate",
    {},
    `模板${new Date().getTime()}.xlsx`
  );
}
/** 提交导入的文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

/** 查询列表 */
function getList() {
  loading.value = true;
  stashQuestionList({
    ...queryParams.value,
    params:{
      beginTime: dateRange.value?dateRange.value[0]:'',
      endTime: dateRange.value?dateRange.value[1]:''
    }
    }).then(response => {
    questionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 考题类型
function getquestionTList() {
  loading.value = true;
  questionTypeList(queryParams.value).then(response => {
    quesTypeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 考点列表
function getsiteIdList() {
  loading.value = true;
  pointTypeList(queryParams.value).then(response => {
    siteIdList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 考试难度列表
function getlevellistData(type) {
  loading.value = true;
  listData({
    pageNum: 1,
    pageSize: 100,
    dictType: type
  }).then(response => {
    if(type === 'sys_question_type'){
      questypeList1.value = response.rows;
    }else{
      quesLevelList.value = response.rows;
    }
    total.value = response.total;
    loading.value = false;

    console.log(questypeList1.value,'questypeList1.value');
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {};
  proxy.resetForm("noticeRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.noticeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增";
  questionType.value = '单选题'
  form.value.quesLevel = '1701069220014886914'
  
  // 选项列表清空
  answList.value = [
  {
    answContent: '',
    answFlag: false, 
  }
]
}
function handleImport() {
  upload.title = "导入";
  upload.open = true;
}
/**修改按钮操作 */
function handleUpdate(row) {
   
  reset();
   console.log(row,'f');
    open.value = true;
    title.value = "编辑";
    form.value.quesId = row.quesId
    form.value.quesType =  row.quesType
    form.value.quesLevel =  row.quesLevel
    form.value.questionType =  row.questionType
    form.value.quesTitle =  row.quesTitle
    form.value.quesScore =  row.quesScore
    form.value.siteId = row.siteId
    form.value.quesAnswer = row.quesAnswer

    // 单选、多选、判断回显
    questypeList1.value.map((item,index)=>{
        if(form.value.questionType == item.dictCode){
          questionType.value = item.dictLabel
        }
    })
    // 选项列表回显
    answList.value = row.answList.map((item,index)=>{
        return {
          answContent: item.answContent,
          answFlag: item.answFlag, 
        }
    })
    
}


/** 提交按钮 */
function submitForm() {

   if(!(answList.value&&answList.value.length)){
    proxy.$modal.msgSuccess("请添加考题选项");
        return
   }
    // 给单选和多选的每个选项加上A,B,C,D...
   answList.value.map((item,index) => {
      item.answSerial = sn(index)
    })

    if(questionType.value === '单选题'||questionType.value === '多选题'){
      let result = answList.value.map((item,index) => {
          return item.answFlag
        })
        console.log(getListItemNumber(result),getListItemNumber(result)[true],'result');
      let objNew = getListItemNumber(result)[true]
      if(!objNew){
        proxy.$modal.msgError("必须有一个选项被选中");
        return
      }
      if(questionType.value === '单选题'&&objNew > 1){
        proxy.$modal.msgError("单选题只能有一个正确选项");
        return
      }
    }
    
  
    // 将多选，单选，判断改为id传过去
    questypeList1.value.map((item,index) => {
      if(questionType.value == item.dictLabel){
        form.value.questionType = item.dictCode
      }
    })
    // 选项数组
   form.value.answList = answList.value

 
  proxy.$refs["noticeRef"].validate(valid => {
    if (valid) {
      if (form.value.quesId != undefined) {
        stashQuestionEdit(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        stashQuestionAdd(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
function sn(index = 0) {
    return String.fromCharCode(65 + index);
}


/** 删除按钮操作 */
function handleDelete(row) {
  const quesId = row.quesId
  proxy.$modal.confirm('是否确认删除该数据项？').then(function() {
    return stashQuestionRomove(quesId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

// 添加一个选项
function handleAddItem(index){
  console.log(index);
  answList.value.splice(index+1,0,{
    answContent: '',
    answFlag: false
  })
  
}

// 删除一个选项
function handleMunisItem(index){
  console.log(index);
  answList.value.splice(index,1)
}

// 上移
function handleUpItem(index){
  if(index === 0) return
  [ answList.value[index-1] ,answList.value[index] ] = [ answList.value[index] ,answList.value[index-1] ]
}

// 下移
function handleDownItem(index){
  let len = answList.value.length
  if(index+1 === len) return
  [ answList.value[index] ,answList.value[index+1] ] = [ answList.value[index+1] ,answList.value[index] ]
}

getsiteIdList()
getlevellistData('sys_question_difficulty') 
getlevellistData('sys_question_type')
getquestionTList()
getList();
</script>
<style scoped lang="scss">
:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #265DA4 !important; //修改默认的背景色
}
.editIcon{
  cursor: pointer;
  margin:0 5px;
}
.inputDeep {
      :deep(.el-input__inner) {
            width: 192px !important;
      }
}
</style>
